package com.jishuo.base.util;

import org.apache.commons.codec.binary.Base64;

import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

/**
 * 密码加盐后做sm3
 */
public class SaltedPasswordUtil {

    /**
     * 加盐后做sm3
     * @param pwd 原始密码
     * @return
     */
    public static String encode(String pwd) {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[12];
        random.nextBytes(salt);
        String saltString = Base64.encodeBase64String(salt);
        byte[] saltpwd = (saltString + pwd).getBytes(StandardCharsets.UTF_8);
        String sm3Pwd = SM3Util.sm3Hex(saltpwd);
        return saltString + "&&" + sm3Pwd;
    }

    /**
     * 验证密码
     * @param pwd 原始密码
     * @param saltPwd 加盐加密后密码
     * @return
     */
    public static boolean checkPwd(String pwd, String saltPwd) {
        int n = saltPwd.indexOf("&&");
        if (n < 1) return false;
        String saltString = saltPwd.substring(0, n);
        byte[] saltpwd = (saltString + pwd).getBytes(StandardCharsets.UTF_8);
        String sm3Pwd = SM3Util.sm3Hex(saltpwd);
        return sm3Pwd.equals(saltPwd.substring(n + 2));
    }
}
